import 'package:flutter/material.dart';
import 'package:flutter_deer/util/toast_utils.dart';

typedef QuantityChangedCallback = void Function(int newQuantity);

class CartItemQuantityPicker extends StatefulWidget {
  final int initialQuantity;
  final QuantityChangedCallback onQuantityChanged;
  // 添加 maxQuantity 参数，默认值为 null 表示不限制
  final int? maxQuantity;

  const CartItemQuantityPicker({
    Key? key,
    required this.initialQuantity,
    required this.onQuantityChanged,
    this.maxQuantity,
  }) : super(key: key);

  @override
  _CartItemQuantityPickerState createState() => _CartItemQuantityPickerState();
}

class _CartItemQuantityPickerState extends State<CartItemQuantityPicker> {
  late int _quantity;

  @override
  void initState() {
    super.initState();
    _quantity = widget.initialQuantity;
  }

  @override
  void didUpdateWidget(covariant CartItemQuantityPicker oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.initialQuantity != widget.initialQuantity) {
      _quantity = widget.initialQuantity;
    }
    // 添加对 maxQuantity 变化的处理
    if (oldWidget.maxQuantity != widget.maxQuantity) {
      // 如果当前数量超过了新的最大值，则调整为最大值
      if (widget.maxQuantity != null && _quantity > widget.maxQuantity!) {
        setState(() {
          _quantity = widget.maxQuantity!;
          widget.onQuantityChanged(_quantity);
        });
      }
    }
  }

  Future<void> _showInputDialog() async {
    final TextEditingController controller = TextEditingController(text: _quantity.toString());

    await showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('修改数量'),
        content: TextField(
          controller: controller,
          keyboardType: TextInputType.number,
          autofocus: true,
          decoration: const InputDecoration(hintText: "请输入数量"),
        ),
        actions: [
          TextButton(
            onPressed: Navigator.of(context).pop,
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              final String value = controller.text.trim();
              if (value.isNotEmpty && int.tryParse(value) != null && int.parse(value) > 0) {
                final int newQuantity = int.parse(value);
                // 检查新数量是否超过最大限制
                if (widget.maxQuantity != null && newQuantity > widget.maxQuantity!) {
                  Toast.show("数量不能超过 ${widget.maxQuantity}");
                  return;
                }
                setState(() {
                  _quantity = newQuantity;
                });
                widget.onQuantityChanged(newQuantity);
                Navigator.of(context).pop();
              } else {
                Toast.show("请输入有效的正整数");
              }
            },
            child: const Text('确定'),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 减号按钮
        Container(
          width: 26,
          height: 26,
          decoration: BoxDecoration(
            color: _quantity <= 1 ? Colors.grey[300] : Theme.of(context).primaryColor.withOpacity(0.25), // 默认背景色
            borderRadius: BorderRadius.circular(6), // 圆角
          ),
          child: IconButton(
            icon: const Icon(Icons.remove),
            onPressed: () {
              if (_quantity > 1) {
                setState(() {
                  _quantity--;
                });
                widget.onQuantityChanged(_quantity);
              }
            },
            color: _quantity <= 1 ? Colors.grey : Theme.of(context).primaryColor,
            splashRadius: 16,
            iconSize: 18,
            padding: const EdgeInsets.all(4),
          ),
        ),

        // 数字显示区域 - 固定宽度 + 自动缩放字体 + 点击弹窗
        Container(
          width: 40, // 固定宽度
          alignment: Alignment.center,
          child: InkWell(
            onTap: _showInputDialog,
            child: FittedBox(
              fit: BoxFit.scaleDown,
              child: Text(
                '$_quantity',
                maxLines: 1,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),

        // 加号按钮
        Container(
          width: 26,
          height: 26,
          decoration: BoxDecoration(
            color: _quantity >= (widget.maxQuantity ?? double.infinity) ? Colors.grey[300] : Theme.of(context).primaryColor.withOpacity(0.25),
            borderRadius: BorderRadius.circular(6),
          ),
          child: IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              if (widget.maxQuantity == null || _quantity < widget.maxQuantity!) {
                setState(() {
                  _quantity++;
                });
                widget.onQuantityChanged(_quantity);
              }
            },
            color: _quantity >= (widget.maxQuantity ?? double.infinity) ? Colors.grey : Theme.of(context).primaryColor,
            splashRadius: 16,
            iconSize: 18,
            padding: const EdgeInsets.all(4),
          ),
        ),
      ],
    );
  }
}
